Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [3]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = 'train.p'
validation_file= 'valid.p'
testing_file = 'test.p'

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

print("Training_features: ", X_train.shape)
print("Training_labels: ", y_train.shape)

print("Testing_features: ", X_test.shape)
print("Testing_labels: ", y_test.shape)

print("Validating_features: ", X_valid.shape)
print("validating_labels: ", y_valid.shape)

print()

print("Image Shape: ", X_train[0].shape)
print("Training Set: ", len(X_train))
print("Validation Set: ", len(X_valid))
print("Testing Set: ", len(X_test))
Training_features:  (34799, 32, 32, 3)
Training_labels:  (34799,)
Testing_features:  (12630, 32, 32, 3)
Testing_labels:  (12630,)
Validating_features:  (4410, 32, 32, 3)
validating_labels:  (4410,)

Image Shape:  (32, 32, 3)
Training Set:  34799
Validation Set:  4410
Testing Set:  12630

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [4]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results

import numpy as np

# TODO: Number of training examples
n_train = len(X_train)

# TODO: Number of validation examples
n_validation = len(X_valid)

# TODO: Number of testing examples.
n_test = len(X_test)

# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape

# TODO: How many unique classes/labels there are in the dataset.
n_classes = len(np.unique(y_train))

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?

In [5]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
import random
import pandas as pd
import numpy as np
from random import sample
# Visualizations will be shown in the notebook.
%matplotlib inline

def getSignNames():
    sign_name = pd.read_csv('signnames.csv').values
    return sign_name

# print(getSignNames()[0][0])

def plotImagesSamples(X, y, samples_to_draw=15, cmap=None):
    sign_samples = np.bincount(y)
    for sign in getSignNames():
        print("Sign: ", sign[1], " ", "Sign_number: ", sign[0], "  -  ", "Number of Samples: ", sign_samples[sign[0]])
        all_samples_indicies = np.where(y==sign[0])[0]
        random_samples = sample(list(all_samples_indicies), samples_to_draw)
        fig = plt.figure(figsize=(samples_to_draw,1))
        
        for item_idx, item in enumerate(range(samples_to_draw)):
            image = X[random_samples[item_idx]]
            axis = fig.add_subplot(1,samples_to_draw,item_idx+1)
            axis.imshow(image, cmap=cmap)
        plt.show()
In [499]:
print("----------Training Images Samples----------")
plotImagesSamples(X_train, y_train)

print("----------Validation Images Samples----------")
plotImagesSamples(X_valid, y_valid)

print("----------Testing Images Samples----------")
plotImagesSamples(X_test, y_test)
----------Training Images Samples----------
Sign:  Speed limit (20km/h)   Sign_number:  0   -   Number of Samples:  180
Sign:  Speed limit (30km/h)   Sign_number:  1   -   Number of Samples:  1980
Sign:  Speed limit (50km/h)   Sign_number:  2   -   Number of Samples:  2010
Sign:  Speed limit (60km/h)   Sign_number:  3   -   Number of Samples:  1260
Sign:  Speed limit (70km/h)   Sign_number:  4   -   Number of Samples:  1770
Sign:  Speed limit (80km/h)   Sign_number:  5   -   Number of Samples:  1650
Sign:  End of speed limit (80km/h)   Sign_number:  6   -   Number of Samples:  360
Sign:  Speed limit (100km/h)   Sign_number:  7   -   Number of Samples:  1290
Sign:  Speed limit (120km/h)   Sign_number:  8   -   Number of Samples:  1260
Sign:  No passing   Sign_number:  9   -   Number of Samples:  1320
Sign:  No passing for vehicles over 3.5 metric tons   Sign_number:  10   -   Number of Samples:  1800
Sign:  Right-of-way at the next intersection   Sign_number:  11   -   Number of Samples:  1170
Sign:  Priority road   Sign_number:  12   -   Number of Samples:  1890
Sign:  Yield   Sign_number:  13   -   Number of Samples:  1920
Sign:  Stop   Sign_number:  14   -   Number of Samples:  690
Sign:  No vehicles   Sign_number:  15   -   Number of Samples:  540
Sign:  Vehicles over 3.5 metric tons prohibited   Sign_number:  16   -   Number of Samples:  360
Sign:  No entry   Sign_number:  17   -   Number of Samples:  990
Sign:  General caution   Sign_number:  18   -   Number of Samples:  1080
Sign:  Dangerous curve to the left   Sign_number:  19   -   Number of Samples:  180
Sign:  Dangerous curve to the right   Sign_number:  20   -   Number of Samples:  300
Sign:  Double curve   Sign_number:  21   -   Number of Samples:  270
Sign:  Bumpy road   Sign_number:  22   -   Number of Samples:  330
Sign:  Slippery road   Sign_number:  23   -   Number of Samples:  450
Sign:  Road narrows on the right   Sign_number:  24   -   Number of Samples:  240
Sign:  Road work   Sign_number:  25   -   Number of Samples:  1350
Sign:  Traffic signals   Sign_number:  26   -   Number of Samples:  540
Sign:  Pedestrians   Sign_number:  27   -   Number of Samples:  210
Sign:  Children crossing   Sign_number:  28   -   Number of Samples:  480
Sign:  Bicycles crossing   Sign_number:  29   -   Number of Samples:  240
Sign:  Beware of ice/snow   Sign_number:  30   -   Number of Samples:  390
Sign:  Wild animals crossing   Sign_number:  31   -   Number of Samples:  690
Sign:  End of all speed and passing limits   Sign_number:  32   -   Number of Samples:  210
Sign:  Turn right ahead   Sign_number:  33   -   Number of Samples:  599
Sign:  Turn left ahead   Sign_number:  34   -   Number of Samples:  360
Sign:  Ahead only   Sign_number:  35   -   Number of Samples:  1080
Sign:  Go straight or right   Sign_number:  36   -   Number of Samples:  330
Sign:  Go straight or left   Sign_number:  37   -   Number of Samples:  180
Sign:  Keep right   Sign_number:  38   -   Number of Samples:  1860
Sign:  Keep left   Sign_number:  39   -   Number of Samples:  270
Sign:  Roundabout mandatory   Sign_number:  40   -   Number of Samples:  300
Sign:  End of no passing   Sign_number:  41   -   Number of Samples:  210
Sign:  End of no passing by vehicles over 3.5 metric tons   Sign_number:  42   -   Number of Samples:  210
----------Validation Images Samples----------
Sign:  Speed limit (20km/h)   Sign_number:  0   -   Number of Samples:  30
Sign:  Speed limit (30km/h)   Sign_number:  1   -   Number of Samples:  240
Sign:  Speed limit (50km/h)   Sign_number:  2   -   Number of Samples:  240
Sign:  Speed limit (60km/h)   Sign_number:  3   -   Number of Samples:  150
Sign:  Speed limit (70km/h)   Sign_number:  4   -   Number of Samples:  210
Sign:  Speed limit (80km/h)   Sign_number:  5   -   Number of Samples:  210
Sign:  End of speed limit (80km/h)   Sign_number:  6   -   Number of Samples:  60
Sign:  Speed limit (100km/h)   Sign_number:  7   -   Number of Samples:  150
Sign:  Speed limit (120km/h)   Sign_number:  8   -   Number of Samples:  150
Sign:  No passing   Sign_number:  9   -   Number of Samples:  150
Sign:  No passing for vehicles over 3.5 metric tons   Sign_number:  10   -   Number of Samples:  210
Sign:  Right-of-way at the next intersection   Sign_number:  11   -   Number of Samples:  150
Sign:  Priority road   Sign_number:  12   -   Number of Samples:  210
Sign:  Yield   Sign_number:  13   -   Number of Samples:  240
Sign:  Stop   Sign_number:  14   -   Number of Samples:  90
Sign:  No vehicles   Sign_number:  15   -   Number of Samples:  90
Sign:  Vehicles over 3.5 metric tons prohibited   Sign_number:  16   -   Number of Samples:  60
Sign:  No entry   Sign_number:  17   -   Number of Samples:  120
Sign:  General caution   Sign_number:  18   -   Number of Samples:  120
Sign:  Dangerous curve to the left   Sign_number:  19   -   Number of Samples:  30
Sign:  Dangerous curve to the right   Sign_number:  20   -   Number of Samples:  60
Sign:  Double curve   Sign_number:  21   -   Number of Samples:  60
Sign:  Bumpy road   Sign_number:  22   -   Number of Samples:  60
Sign:  Slippery road   Sign_number:  23   -   Number of Samples:  60
Sign:  Road narrows on the right   Sign_number:  24   -   Number of Samples:  30
Sign:  Road work   Sign_number:  25   -   Number of Samples:  150
Sign:  Traffic signals   Sign_number:  26   -   Number of Samples:  60
Sign:  Pedestrians   Sign_number:  27   -   Number of Samples:  30
Sign:  Children crossing   Sign_number:  28   -   Number of Samples:  60
Sign:  Bicycles crossing   Sign_number:  29   -   Number of Samples:  30
Sign:  Beware of ice/snow   Sign_number:  30   -   Number of Samples:  60
Sign:  Wild animals crossing   Sign_number:  31   -   Number of Samples:  90
Sign:  End of all speed and passing limits   Sign_number:  32   -   Number of Samples:  30
Sign:  Turn right ahead   Sign_number:  33   -   Number of Samples:  90
Sign:  Turn left ahead   Sign_number:  34   -   Number of Samples:  60
Sign:  Ahead only   Sign_number:  35   -   Number of Samples:  120
Sign:  Go straight or right   Sign_number:  36   -   Number of Samples:  60
Sign:  Go straight or left   Sign_number:  37   -   Number of Samples:  30
Sign:  Keep right   Sign_number:  38   -   Number of Samples:  210
Sign:  Keep left   Sign_number:  39   -   Number of Samples:  30
Sign:  Roundabout mandatory   Sign_number:  40   -   Number of Samples:  60
Sign:  End of no passing   Sign_number:  41   -   Number of Samples:  30
Sign:  End of no passing by vehicles over 3.5 metric tons   Sign_number:  42   -   Number of Samples:  30
----------Testing Images Samples----------
Sign:  Speed limit (20km/h)   Sign_number:  0   -   Number of Samples:  60
Sign:  Speed limit (30km/h)   Sign_number:  1   -   Number of Samples:  720
Sign:  Speed limit (50km/h)   Sign_number:  2   -   Number of Samples:  750
Sign:  Speed limit (60km/h)   Sign_number:  3   -   Number of Samples:  450
Sign:  Speed limit (70km/h)   Sign_number:  4   -   Number of Samples:  660
Sign:  Speed limit (80km/h)   Sign_number:  5   -   Number of Samples:  630
Sign:  End of speed limit (80km/h)   Sign_number:  6   -   Number of Samples:  150
Sign:  Speed limit (100km/h)   Sign_number:  7   -   Number of Samples:  450
Sign:  Speed limit (120km/h)   Sign_number:  8   -   Number of Samples:  450
Sign:  No passing   Sign_number:  9   -   Number of Samples:  480
Sign:  No passing for vehicles over 3.5 metric tons   Sign_number:  10   -   Number of Samples:  660
Sign:  Right-of-way at the next intersection   Sign_number:  11   -   Number of Samples:  420
Sign:  Priority road   Sign_number:  12   -   Number of Samples:  690
Sign:  Yield   Sign_number:  13   -   Number of Samples:  720
Sign:  Stop   Sign_number:  14   -   Number of Samples:  270
Sign:  No vehicles   Sign_number:  15   -   Number of Samples:  210
Sign:  Vehicles over 3.5 metric tons prohibited   Sign_number:  16   -   Number of Samples:  150
Sign:  No entry   Sign_number:  17   -   Number of Samples:  360
Sign:  General caution   Sign_number:  18   -   Number of Samples:  390
Sign:  Dangerous curve to the left   Sign_number:  19   -   Number of Samples:  60
Sign:  Dangerous curve to the right   Sign_number:  20   -   Number of Samples:  90
Sign:  Double curve   Sign_number:  21   -   Number of Samples:  90
Sign:  Bumpy road   Sign_number:  22   -   Number of Samples:  120
Sign:  Slippery road   Sign_number:  23   -   Number of Samples:  150
Sign:  Road narrows on the right   Sign_number:  24   -   Number of Samples:  90
Sign:  Road work   Sign_number:  25   -   Number of Samples:  480
Sign:  Traffic signals   Sign_number:  26   -   Number of Samples:  180
Sign:  Pedestrians   Sign_number:  27   -   Number of Samples:  60
Sign:  Children crossing   Sign_number:  28   -   Number of Samples:  150
Sign:  Bicycles crossing   Sign_number:  29   -   Number of Samples:  90
Sign:  Beware of ice/snow   Sign_number:  30   -   Number of Samples:  150
Sign:  Wild animals crossing   Sign_number:  31   -   Number of Samples:  270
Sign:  End of all speed and passing limits   Sign_number:  32   -   Number of Samples:  60
Sign:  Turn right ahead   Sign_number:  33   -   Number of Samples:  210
Sign:  Turn left ahead   Sign_number:  34   -   Number of Samples:  120
Sign:  Ahead only   Sign_number:  35   -   Number of Samples:  390
Sign:  Go straight or right   Sign_number:  36   -   Number of Samples:  120
Sign:  Go straight or left   Sign_number:  37   -   Number of Samples:  60
Sign:  Keep right   Sign_number:  38   -   Number of Samples:  690
Sign:  Keep left   Sign_number:  39   -   Number of Samples:  90
Sign:  Roundabout mandatory   Sign_number:  40   -   Number of Samples:  90
Sign:  End of no passing   Sign_number:  41   -   Number of Samples:  60
Sign:  End of no passing by vehicles over 3.5 metric tons   Sign_number:  42   -   Number of Samples:  90
In [6]:
# plot histograms

def plot_histogram(y):
    classes = pd.DataFrame()
    classes['label'] = y
    ax = classes['label'].value_counts().plot(kind='barh', figsize = (10,10), title='Image count')
    ax.set_yticklabels(list(map(lambda x: getSignNames()[x][1], classes['label'].value_counts().index.tolist()))) 

    for i, v in enumerate(classes['label'].value_counts()):
        ax.text(v + 3, i - 0.25, str(v), color='blue')


# Training Histogram
plt.title("Training Histogram")
plt.hist(y_train, bins=n_classes)
plt.show()
plot_histogram(y_train)
plt.show()

# Validation Histogram
plt.title("Validation Histogram")
plt.hist(y_valid, bins=n_classes)
plt.show()
plot_histogram(y_valid)
plt.show()

# Testing Histogram
plt.title("Testing Histogram")
plt.hist(y_test, bins=n_classes)
plt.show()
plot_histogram(y_test)
plt.show()

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.

Other pre-processing steps are optional. You can try different techniques to see if it improves performance.

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [7]:
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include 
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.

import cv2

def NormalizeImage(img):
    max_pixel_value = 255
    return (img - img.mean())/img.mean()

def GrayScaleImage(img):
    gray_image = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#     gray_image = np.expand_dims(gray_image,axis=3)
    return gray_image

def PreProcessingImages(images):
    returnImages = []
    for img in images:
        returnImages.append(NormalizeImage(GrayScaleImage(img)))
    return returnImages
In [18]:
X_train_processed = PreProcessingImages(X_train)
X_valid_processed = PreProcessingImages(X_valid)
X_test_processed = PreProcessingImages(X_test)

print(X_train_processed[0].shape)

print("----------Training Images Samples----------")
plotImagesSamples(X_train_processed, y_train, cmap='gray')

print("----------Validation Images Samples----------")
plotImagesSamples(X_valid_processed, y_valid,cmap='gray')

print("----------Testing Images Samples----------")
plotImagesSamples(X_test_processed, y_test, cmap='gray')
(32, 32)
----------Training Images Samples----------
Sign:  Speed limit (20km/h)   Sign_number:  0   -   Number of Samples:  180
Sign:  Speed limit (30km/h)   Sign_number:  1   -   Number of Samples:  1980
Sign:  Speed limit (50km/h)   Sign_number:  2   -   Number of Samples:  2010
Sign:  Speed limit (60km/h)   Sign_number:  3   -   Number of Samples:  1260
Sign:  Speed limit (70km/h)   Sign_number:  4   -   Number of Samples:  1770
Sign:  Speed limit (80km/h)   Sign_number:  5   -   Number of Samples:  1650
Sign:  End of speed limit (80km/h)   Sign_number:  6   -   Number of Samples:  360
Sign:  Speed limit (100km/h)   Sign_number:  7   -   Number of Samples:  1290
Sign:  Speed limit (120km/h)   Sign_number:  8   -   Number of Samples:  1260
Sign:  No passing   Sign_number:  9   -   Number of Samples:  1320
Sign:  No passing for vehicles over 3.5 metric tons   Sign_number:  10   -   Number of Samples:  1800
Sign:  Right-of-way at the next intersection   Sign_number:  11   -   Number of Samples:  1170
Sign:  Priority road   Sign_number:  12   -   Number of Samples:  1890
Sign:  Yield   Sign_number:  13   -   Number of Samples:  1920
Sign:  Stop   Sign_number:  14   -   Number of Samples:  690
Sign:  No vehicles   Sign_number:  15   -   Number of Samples:  540
Sign:  Vehicles over 3.5 metric tons prohibited   Sign_number:  16   -   Number of Samples:  360
Sign:  No entry   Sign_number:  17   -   Number of Samples:  990
Sign:  General caution   Sign_number:  18   -   Number of Samples:  1080
Sign:  Dangerous curve to the left   Sign_number:  19   -   Number of Samples:  180
Sign:  Dangerous curve to the right   Sign_number:  20   -   Number of Samples:  300
Sign:  Double curve   Sign_number:  21   -   Number of Samples:  270
Sign:  Bumpy road   Sign_number:  22   -   Number of Samples:  330
Sign:  Slippery road   Sign_number:  23   -   Number of Samples:  450
Sign:  Road narrows on the right   Sign_number:  24   -   Number of Samples:  240
Sign:  Road work   Sign_number:  25   -   Number of Samples:  1350
Sign:  Traffic signals   Sign_number:  26   -   Number of Samples:  540
Sign:  Pedestrians   Sign_number:  27   -   Number of Samples:  210
Sign:  Children crossing   Sign_number:  28   -   Number of Samples:  480
Sign:  Bicycles crossing   Sign_number:  29   -   Number of Samples:  240
Sign:  Beware of ice/snow   Sign_number:  30   -   Number of Samples:  390
Sign:  Wild animals crossing   Sign_number:  31   -   Number of Samples:  690
Sign:  End of all speed and passing limits   Sign_number:  32   -   Number of Samples:  210
Sign:  Turn right ahead   Sign_number:  33   -   Number of Samples:  599
Sign:  Turn left ahead   Sign_number:  34   -   Number of Samples:  360
Sign:  Ahead only   Sign_number:  35   -   Number of Samples:  1080
Sign:  Go straight or right   Sign_number:  36   -   Number of Samples:  330
Sign:  Go straight or left   Sign_number:  37   -   Number of Samples:  180
Sign:  Keep right   Sign_number:  38   -   Number of Samples:  1860
Sign:  Keep left   Sign_number:  39   -   Number of Samples:  270
Sign:  Roundabout mandatory   Sign_number:  40   -   Number of Samples:  300
Sign:  End of no passing   Sign_number:  41   -   Number of Samples:  210
Sign:  End of no passing by vehicles over 3.5 metric tons   Sign_number:  42   -   Number of Samples:  210
----------Validation Images Samples----------
Sign:  Speed limit (20km/h)   Sign_number:  0   -   Number of Samples:  30
Sign:  Speed limit (30km/h)   Sign_number:  1   -   Number of Samples:  240
Sign:  Speed limit (50km/h)   Sign_number:  2   -   Number of Samples:  240
Sign:  Speed limit (60km/h)   Sign_number:  3   -   Number of Samples:  150
Sign:  Speed limit (70km/h)   Sign_number:  4   -   Number of Samples:  210
Sign:  Speed limit (80km/h)   Sign_number:  5   -   Number of Samples:  210
Sign:  End of speed limit (80km/h)   Sign_number:  6   -   Number of Samples:  60
Sign:  Speed limit (100km/h)   Sign_number:  7   -   Number of Samples:  150
Sign:  Speed limit (120km/h)   Sign_number:  8   -   Number of Samples:  150
Sign:  No passing   Sign_number:  9   -   Number of Samples:  150
Sign:  No passing for vehicles over 3.5 metric tons   Sign_number:  10   -   Number of Samples:  210
Sign:  Right-of-way at the next intersection   Sign_number:  11   -   Number of Samples:  150
Sign:  Priority road   Sign_number:  12   -   Number of Samples:  210
Sign:  Yield   Sign_number:  13   -   Number of Samples:  240
Sign:  Stop   Sign_number:  14   -   Number of Samples:  90
Sign:  No vehicles   Sign_number:  15   -   Number of Samples:  90
Sign:  Vehicles over 3.5 metric tons prohibited   Sign_number:  16   -   Number of Samples:  60
Sign:  No entry   Sign_number:  17   -   Number of Samples:  120
Sign:  General caution   Sign_number:  18   -   Number of Samples:  120
Sign:  Dangerous curve to the left   Sign_number:  19   -   Number of Samples:  30
Sign:  Dangerous curve to the right   Sign_number:  20   -   Number of Samples:  60
Sign:  Double curve   Sign_number:  21   -   Number of Samples:  60
Sign:  Bumpy road   Sign_number:  22   -   Number of Samples:  60
Sign:  Slippery road   Sign_number:  23   -   Number of Samples:  60
Sign:  Road narrows on the right   Sign_number:  24   -   Number of Samples:  30
Sign:  Road work   Sign_number:  25   -   Number of Samples:  150
Sign:  Traffic signals   Sign_number:  26   -   Number of Samples:  60
Sign:  Pedestrians   Sign_number:  27   -   Number of Samples:  30
Sign:  Children crossing   Sign_number:  28   -   Number of Samples:  60
Sign:  Bicycles crossing   Sign_number:  29   -   Number of Samples:  30
Sign:  Beware of ice/snow   Sign_number:  30   -   Number of Samples:  60
Sign:  Wild animals crossing   Sign_number:  31   -   Number of Samples:  90
Sign:  End of all speed and passing limits   Sign_number:  32   -   Number of Samples:  30
Sign:  Turn right ahead   Sign_number:  33   -   Number of Samples:  90
Sign:  Turn left ahead   Sign_number:  34   -   Number of Samples:  60
Sign:  Ahead only   Sign_number:  35   -   Number of Samples:  120
Sign:  Go straight or right   Sign_number:  36   -   Number of Samples:  60
Sign:  Go straight or left   Sign_number:  37   -   Number of Samples:  30
Sign:  Keep right   Sign_number:  38   -   Number of Samples:  210
Sign:  Keep left   Sign_number:  39   -   Number of Samples:  30
Sign:  Roundabout mandatory   Sign_number:  40   -   Number of Samples:  60
Sign:  End of no passing   Sign_number:  41   -   Number of Samples:  30
Sign:  End of no passing by vehicles over 3.5 metric tons   Sign_number:  42   -   Number of Samples:  30
----------Testing Images Samples----------
Sign:  Speed limit (20km/h)   Sign_number:  0   -   Number of Samples:  60
Sign:  Speed limit (30km/h)   Sign_number:  1   -   Number of Samples:  720
Sign:  Speed limit (50km/h)   Sign_number:  2   -   Number of Samples:  750
Sign:  Speed limit (60km/h)   Sign_number:  3   -   Number of Samples:  450
Sign:  Speed limit (70km/h)   Sign_number:  4   -   Number of Samples:  660
Sign:  Speed limit (80km/h)   Sign_number:  5   -   Number of Samples:  630
Sign:  End of speed limit (80km/h)   Sign_number:  6   -   Number of Samples:  150
Sign:  Speed limit (100km/h)   Sign_number:  7   -   Number of Samples:  450
Sign:  Speed limit (120km/h)   Sign_number:  8   -   Number of Samples:  450
Sign:  No passing   Sign_number:  9   -   Number of Samples:  480
Sign:  No passing for vehicles over 3.5 metric tons   Sign_number:  10   -   Number of Samples:  660
Sign:  Right-of-way at the next intersection   Sign_number:  11   -   Number of Samples:  420
Sign:  Priority road   Sign_number:  12   -   Number of Samples:  690
Sign:  Yield   Sign_number:  13   -   Number of Samples:  720
Sign:  Stop   Sign_number:  14   -   Number of Samples:  270
Sign:  No vehicles   Sign_number:  15   -   Number of Samples:  210
Sign:  Vehicles over 3.5 metric tons prohibited   Sign_number:  16   -   Number of Samples:  150
Sign:  No entry   Sign_number:  17   -   Number of Samples:  360
Sign:  General caution   Sign_number:  18   -   Number of Samples:  390
Sign:  Dangerous curve to the left   Sign_number:  19   -   Number of Samples:  60
Sign:  Dangerous curve to the right   Sign_number:  20   -   Number of Samples:  90
Sign:  Double curve   Sign_number:  21   -   Number of Samples:  90
Sign:  Bumpy road   Sign_number:  22   -   Number of Samples:  120
Sign:  Slippery road   Sign_number:  23   -   Number of Samples:  150
Sign:  Road narrows on the right   Sign_number:  24   -   Number of Samples:  90
Sign:  Road work   Sign_number:  25   -   Number of Samples:  480
Sign:  Traffic signals   Sign_number:  26   -   Number of Samples:  180
Sign:  Pedestrians   Sign_number:  27   -   Number of Samples:  60
Sign:  Children crossing   Sign_number:  28   -   Number of Samples:  150
Sign:  Bicycles crossing   Sign_number:  29   -   Number of Samples:  90
Sign:  Beware of ice/snow   Sign_number:  30   -   Number of Samples:  150
Sign:  Wild animals crossing   Sign_number:  31   -   Number of Samples:  270
Sign:  End of all speed and passing limits   Sign_number:  32   -   Number of Samples:  60
Sign:  Turn right ahead   Sign_number:  33   -   Number of Samples:  210
Sign:  Turn left ahead   Sign_number:  34   -   Number of Samples:  120
Sign:  Ahead only   Sign_number:  35   -   Number of Samples:  390
Sign:  Go straight or right   Sign_number:  36   -   Number of Samples:  120
Sign:  Go straight or left   Sign_number:  37   -   Number of Samples:  60
Sign:  Keep right   Sign_number:  38   -   Number of Samples:  690
Sign:  Keep left   Sign_number:  39   -   Number of Samples:  90
Sign:  Roundabout mandatory   Sign_number:  40   -   Number of Samples:  90
Sign:  End of no passing   Sign_number:  41   -   Number of Samples:  60
Sign:  End of no passing by vehicles over 3.5 metric tons   Sign_number:  42   -   Number of Samples:  90
In [9]:
print("Test: ", X_train_processed[0].shape)
X_train_processed = np.expand_dims(X_train_processed, axis=3)
X_valid_processed = np.expand_dims(X_valid_processed, axis=3)
X_test_processed = np.expand_dims(X_test_processed, axis=3)
print("Test: ", X_train_processed[0].shape)
Test:  (32, 32)
Test:  (32, 32, 1)

Model Architecture

In [10]:
### Define your architecture here.
### Feel free to use as many code cells as needed.

from tensorflow.contrib.layers import flatten

import tensorflow as tf

def LeNet(x):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1

    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 1, 48), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros([48]))
    conv1 = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID')
    conv1 = tf.nn.bias_add(conv1, conv1_b)
    conv1 = tf.nn.relu(conv1)

    # Max Pooling. Input = 28x28x48. Output = 14x14x48.
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
    
    # dropout 
    conv1 = tf.nn.dropout(conv1, keep_prob)
    
    
    # Convolutional Layer. Output = 10x10x96.
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, 48, 96), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros([96]))
    conv2 = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID')
    conv2 = tf.nn.bias_add(conv2, conv2_b)
    conv2 = tf.nn.relu(conv2)

    # Max Pooling. Input = 10x10x96. Output = 5x5x96.
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
    
    # dropout 
    conv2 = tf.nn.dropout(conv2, keep_prob)
    
    
    # Convolutional Layer. Input = 5x5x96. Output = 3x3x172.
    conv3_W = tf.Variable(tf.truncated_normal(shape=(3, 3, 96, 172), mean = mu, stddev = sigma))
    conv3_b = tf.Variable(tf.zeros([172]))
    conv3 = tf.nn.conv2d(conv2, conv3_W, strides=[1, 1, 1, 1], padding='VALID', name='conv3')
    conv3 = tf.nn.bias_add(conv3, conv3_b)
    conv3 = tf.nn.relu(conv3)
    
    # Max Pooling. Input = 3x3x172. Output = 2x2x172.
    conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 1, 1, 1], padding='VALID')
    
    # Flatten. Input = 2x2x172. Output = 688.
    fc1 = flatten(conv3)
    
    # dropout
    fc1 = tf.nn.dropout(fc1, keep_prob)
    
    
    
    # Fully Connected. Input = 688. Output = 84.
    fc2_W = tf.Variable(tf.truncated_normal(shape=(688 , 84), mean = mu, stddev = sigma))
    fc2_b = tf.Variable(tf.zeros([84]))
    fc2 = tf.add(tf.matmul(fc1,fc2_W), fc2_b)
    fc2 = tf.nn.relu(fc2)
    
    # dropout
    fc2 = tf.nn.dropout(fc2, keep_prob)

    # Fully Connected. Input = 84. Output = 43.
    fc3_W = tf.Variable(tf.truncated_normal(shape=(84, n_classes), mean = mu, stddev = sigma))
    fc3_b = tf.Variable(tf.zeros([n_classes]))
    fc3 = tf.add(tf.matmul(fc2,fc3_W), fc3_b)
    logits = fc3
    
    return logits

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [11]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.

from sklearn.utils import shuffle

EPOCHS = 35
BATCH_SIZE = 128


# features and label
x = tf.placeholder(tf.float32, (None, 32, 32, 1))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)
keep_prob = tf.placeholder(tf.float32)
#################################################################################
#training pipeline
rate = 0.0009

logits = LeNet(x)
print("logits shape", logits)
print("One hot shape", one_hot_y)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y, logits=logits)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)
#################################################################################
# Model Evaluation
correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, keep_prob: 1.0})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples
##################################################################################
# Train the Model
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train_processed)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        X_t, y_t = shuffle(X_train_processed, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_t[offset:end], y_t[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y, keep_prob:0.5})
            
        Training_Accuracy = evaluate(X_train_processed, y_train)
        print("EPOCH {} ...".format(i+1))
        print("Training Accuracy = {:.3f}".format(Training_Accuracy))
        validation_accuracy = evaluate(X_valid_processed, y_valid)
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
        
    saver.save(sess, './lenet')
    print("Model saved")
##################################################################################
logits shape Tensor("Add_1:0", shape=(?, 43), dtype=float32)
One hot shape Tensor("one_hot:0", dtype=float32)
Training...

EPOCH 1 ...
Training Accuracy = 0.068
Validation Accuracy = 0.066

EPOCH 2 ...
Training Accuracy = 0.297
Validation Accuracy = 0.276

EPOCH 3 ...
Training Accuracy = 0.449
Validation Accuracy = 0.428

EPOCH 4 ...
Training Accuracy = 0.606
Validation Accuracy = 0.560

EPOCH 5 ...
Training Accuracy = 0.707
Validation Accuracy = 0.636

EPOCH 6 ...
Training Accuracy = 0.812
Validation Accuracy = 0.756

EPOCH 7 ...
Training Accuracy = 0.900
Validation Accuracy = 0.844

EPOCH 8 ...
Training Accuracy = 0.925
Validation Accuracy = 0.876

EPOCH 9 ...
Training Accuracy = 0.950
Validation Accuracy = 0.912

EPOCH 10 ...
Training Accuracy = 0.958
Validation Accuracy = 0.923

EPOCH 11 ...
Training Accuracy = 0.967
Validation Accuracy = 0.932

EPOCH 12 ...
Training Accuracy = 0.976
Validation Accuracy = 0.942

EPOCH 13 ...
Training Accuracy = 0.980
Validation Accuracy = 0.954

EPOCH 14 ...
Training Accuracy = 0.985
Validation Accuracy = 0.957

EPOCH 15 ...
Training Accuracy = 0.989
Validation Accuracy = 0.969

EPOCH 16 ...
Training Accuracy = 0.990
Validation Accuracy = 0.965

EPOCH 17 ...
Training Accuracy = 0.992
Validation Accuracy = 0.972

EPOCH 18 ...
Training Accuracy = 0.994
Validation Accuracy = 0.969

EPOCH 19 ...
Training Accuracy = 0.994
Validation Accuracy = 0.975

EPOCH 20 ...
Training Accuracy = 0.994
Validation Accuracy = 0.972

EPOCH 21 ...
Training Accuracy = 0.995
Validation Accuracy = 0.972

EPOCH 22 ...
Training Accuracy = 0.996
Validation Accuracy = 0.973

EPOCH 23 ...
Training Accuracy = 0.996
Validation Accuracy = 0.973

EPOCH 24 ...
Training Accuracy = 0.996
Validation Accuracy = 0.971

EPOCH 25 ...
Training Accuracy = 0.997
Validation Accuracy = 0.972

EPOCH 26 ...
Training Accuracy = 0.998
Validation Accuracy = 0.974

EPOCH 27 ...
Training Accuracy = 0.995
Validation Accuracy = 0.967

EPOCH 28 ...
Training Accuracy = 0.997
Validation Accuracy = 0.974

EPOCH 29 ...
Training Accuracy = 0.998
Validation Accuracy = 0.976

EPOCH 30 ...
Training Accuracy = 0.998
Validation Accuracy = 0.980

EPOCH 31 ...
Training Accuracy = 0.999
Validation Accuracy = 0.976

EPOCH 32 ...
Training Accuracy = 0.998
Validation Accuracy = 0.981

EPOCH 33 ...
Training Accuracy = 0.999
Validation Accuracy = 0.976

EPOCH 34 ...
Training Accuracy = 0.999
Validation Accuracy = 0.979

EPOCH 35 ...
Training Accuracy = 0.999
Validation Accuracy = 0.981

Model saved
In [ ]:
 
In [12]:
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    test_accuracy = evaluate(X_test_processed, y_test)
    print("Test Accuracy = {:.3f}".format(test_accuracy))
Test Accuracy = 0.963

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [13]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import glob 
from scipy.misc import imread
import cv2

Images_Number = 26
fig = plt.figure(figsize=(Images_Number,1))
Labels = np.array([], dtype='uint8')
test_images_added = np.array([], dtype='uint8')

for img_idx, img in enumerate(glob.glob("./Testing_images/*.PNG")):
    labels = img.split("\\")
    labels = labels[1][0:labels[1].index("-")]
    Labels = np.append(Labels, int(labels))
    im = imread(img)
#     print(img, im.shape)
    axis = fig.add_subplot(1,Images_Number,img_idx+1)
    plt.imshow(im)
    
    
    test_images_added = np.append(test_images_added, im)


# print(test_images_added.shape)
test_images_added = np.reshape(test_images_added, (Images_Number,32,32,3))
# print(Labels.shape)
# print(Labels)

# print(np.array(test_images_added).dtype)
# print(test_images_added)

Predict the Sign Type for Each Image

In [14]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.

# pre-processing
test_processed = PreProcessingImages(test_images_added)
fig = plt.figure(figsize=(Images_Number,1))
for img_idx, img in enumerate(test_processed):
    axis = fig.add_subplot(1,Images_Number,img_idx+1)
    plt.imshow(img,cmap='gray')
    
    
# test prediction
test_processed = np.expand_dims(test_processed,axis=3)
print(test_processed.shape)
(26, 32, 32, 1)

Analyze Performance

In [16]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.

softmax = tf.nn.softmax(logits)
top_k = tf.nn.top_k(softmax, k=5)

with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))
    test_accuracy = evaluate(test_processed, Labels)
    softmax_out = sess.run(softmax, feed_dict={x: test_processed, keep_prob: 1.0})
    top_k_out = sess.run(top_k, feed_dict={x: test_processed, keep_prob: 1.0})
    print("Test Accuracy = {:.3f}".format(test_accuracy))
Test Accuracy = 0.923

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [17]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.


print(top_k_out)

fig, ax = plt.subplots(Images_Number,2, figsize=(10,120))
ax = ax.ravel()

for idx, index in enumerate(top_k_out.indices):
    print(getSignNames()[Labels[idx]])
    print(getSignNames()[index[0]])
    print()
    


for i in range(len(softmax_out)*2):
    if i%2 == 0:
        ax[i].imshow(test_images_added[i//2])
        ax[i].set_xlabel(getSignNames()[Labels[i//2]])
    else:
        ax[i].bar(np.arange(n_classes), softmax_out[(i-1)//2])
        ax[i].set_ylabel('Softmax probability')
        ax[i].set_xlabel(getSignNames()[top_k_out.indices[(i-1)//2][0]])
TopKV2(values=array([[  9.67692494e-01,   1.93717144e-02,   7.93897174e-03,
          4.36289655e-03,   2.95312930e-04],
       [  9.94938731e-01,   4.00290918e-03,   5.04737895e-04,
          1.27771287e-04,   8.55640101e-05],
       [  9.99997616e-01,   2.43023851e-06,   4.49315030e-10,
          4.44944483e-13,   2.40414432e-13],
       [  1.00000000e+00,   9.69679476e-11,   3.84142825e-15,
          1.43944305e-18,   2.32028039e-19],
       [  1.00000000e+00,   2.74372077e-16,   1.23394802e-18,
          2.26647811e-20,   3.49877876e-24],
       [  1.00000000e+00,   8.47423211e-18,   1.49669254e-18,
          7.79239396e-19,   5.85889120e-21],
       [  1.00000000e+00,   1.69595591e-25,   2.59372747e-27,
          1.18212888e-29,   2.15729591e-31],
       [  4.97557700e-01,   1.68016240e-01,   4.99336496e-02,
          4.71831486e-02,   4.54424061e-02],
       [  9.96919751e-01,   3.08020669e-03,   4.36346888e-08,
          1.07657492e-08,   5.90702265e-10],
       [  1.00000000e+00,   4.16148854e-15,   4.28877133e-17,
          8.97829721e-20,   1.06401759e-26],
       [  1.00000000e+00,   2.67478573e-08,   7.99735833e-11,
          8.34462274e-13,   3.24678354e-13],
       [  9.99999642e-01,   3.09776794e-07,   5.50884172e-10,
          1.25654114e-11,   1.23513170e-11],
       [  7.96909511e-01,   1.04977034e-01,   8.69150609e-02,
          1.07664894e-02,   2.24919611e-04],
       [  9.99824107e-01,   1.67459773e-04,   8.39789118e-06,
          1.20701941e-07,   1.03107675e-10],
       [  9.99371707e-01,   6.28302980e-04,   5.81938693e-08,
          2.87324369e-08,   2.38498945e-08],
       [  9.85428751e-01,   1.39779979e-02,   5.91569638e-04,
          1.42527222e-06,   1.72659441e-07],
       [  9.98613834e-01,   1.34721084e-03,   3.22560481e-05,
          2.85940268e-06,   2.28997328e-06],
       [  1.00000000e+00,   7.64093717e-14,   2.06057841e-14,
          3.82535749e-15,   1.90298742e-15],
       [  1.00000000e+00,   9.02706176e-09,   3.07771114e-10,
          2.03696074e-10,   3.34314867e-11],
       [  1.00000000e+00,   2.93068694e-12,   4.20002134e-14,
          2.14125304e-14,   8.86108877e-18],
       [  1.00000000e+00,   2.87824154e-13,   3.69105195e-16,
          3.05324838e-17,   1.04499191e-17],
       [  7.31268764e-01,   1.85049921e-01,   1.90520957e-02,
          8.33022036e-03,   7.19230063e-03],
       [  5.84277749e-01,   4.15006191e-01,   4.38208488e-04,
          8.02435388e-05,   2.86778795e-05],
       [  5.05551338e-01,   3.58618826e-01,   7.55442604e-02,
          3.10752615e-02,   1.00370832e-02],
       [  9.26024318e-01,   2.40340196e-02,   2.18105484e-02,
          2.17854921e-02,   1.60254154e-03],
       [  9.99852300e-01,   6.13386510e-05,   5.49120305e-05,
          2.51378751e-05,   4.27430859e-06]], dtype=float32), indices=array([[ 0, 18,  4,  1,  3],
       [ 1,  0,  2, 40,  4],
       [11, 30, 27, 21, 40],
       [11, 30, 27, 40, 21],
       [12, 40, 25, 38, 39],
       [12, 40, 25, 38, 13],
       [13, 15, 12,  2,  1],
       [14,  1, 34,  8,  3],
       [17, 14,  9, 34,  8],
       [18, 26, 27, 11, 25],
       [18, 26, 27, 11, 29],
       [19, 23, 31,  0, 21],
       [ 2,  5,  1,  3, 40],
       [25, 11, 21, 30, 20],
       [ 3,  5,  2,  9,  8],
       [31, 23, 19, 21, 29],
       [32, 41,  6, 18,  3],
       [35, 34,  3, 11, 36],
       [36, 35, 34, 32, 28],
       [37, 11, 12, 35, 40],
       [38, 34, 30, 31, 21],
       [18, 26, 27, 33, 25],
       [40, 12, 38, 25,  3],
       [ 5,  3, 10, 16,  2],
       [ 9, 16,  3, 10, 15],
       [ 9, 10, 16,  3, 41]]))
[0 'Speed limit (20km/h)']
[0 'Speed limit (20km/h)']

[1 'Speed limit (30km/h)']
[1 'Speed limit (30km/h)']

[11 'Right-of-way at the next intersection']
[11 'Right-of-way at the next intersection']

[11 'Right-of-way at the next intersection']
[11 'Right-of-way at the next intersection']

[12 'Priority road']
[12 'Priority road']

[12 'Priority road']
[12 'Priority road']

[13 'Yield']
[13 'Yield']

[14 'Stop']
[14 'Stop']

[17 'No entry']
[17 'No entry']

[18 'General caution']
[18 'General caution']

[18 'General caution']
[18 'General caution']

[19 'Dangerous curve to the left']
[19 'Dangerous curve to the left']

[2 'Speed limit (50km/h)']
[2 'Speed limit (50km/h)']

[25 'Road work']
[25 'Road work']

[3 'Speed limit (60km/h)']
[3 'Speed limit (60km/h)']

[31 'Wild animals crossing']
[31 'Wild animals crossing']

[32 'End of all speed and passing limits']
[32 'End of all speed and passing limits']

[35 'Ahead only']
[35 'Ahead only']

[36 'Go straight or right']
[36 'Go straight or right']

[37 'Go straight or left']
[37 'Go straight or left']

[38 'Keep right']
[38 'Keep right']

[38 'Keep right']
[18 'General caution']

[40 'Roundabout mandatory']
[40 'Roundabout mandatory']

[7 'Speed limit (100km/h)']
[5 'Speed limit (80km/h)']

[9 'No passing']
[9 'No passing']

[9 'No passing']
[9 'No passing']

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.


Step 4 (Optional): Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [490]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
            
In [497]:
Image = test_images_added[2]
plt.imshow(Image)

feed_image = test_processed[2]
feed_image = np.reshape(feed_image, (1,32,32,1))
feed_image = tf.cast(feed_image,dtype=tf.float32)
print(feed_image.dtype)


with tf.Session() as sess:
    # Convolution (layer 3 after 'tf.nn.conv2d' operation)
    saver.restore(sess, tf.train.latest_checkpoint('.'))
#     for op in tf.get_default_graph().get_operations():
#         print(str(op.name))
    conv3 = sess.graph.get_tensor_by_name('Conv2D_2:0')
    outputFeatureMap(feed_image, conv3)
<dtype: 'float32'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-497-e3188532df55> in <module>()
     14 #         print(str(op.name))
     15     conv3 = sess.graph.get_tensor_by_name('Conv2D_2:0')
---> 16     outputFeatureMap(feed_image, conv3)

<ipython-input-490-6da10989b70e> in outputFeatureMap(image_input, tf_activation, activation_min, activation_max, plt_num)
     12     # Note: x should be the same name as your network's tensorflow data placeholder variable
     13     # If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
---> 14     activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
     15     featuremaps = activation.shape[3]
     16     plt.figure(plt_num, figsize=(15,15))

C:\Anaconda\envs\carnd-term1\lib\site-packages\tensorflow\python\framework\ops.py in eval(self, feed_dict, session)
    573 
    574     """
--> 575     return _eval_using_default_session(self, feed_dict, self.graph, session)
    576 
    577 

C:\Anaconda\envs\carnd-term1\lib\site-packages\tensorflow\python\framework\ops.py in _eval_using_default_session(tensors, feed_dict, graph, session)
   3631                        "the tensor's graph is different from the session's "
   3632                        "graph.")
-> 3633   return session.run(tensors, feed_dict)
   3634 
   3635 

C:\Anaconda\envs\carnd-term1\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    764     try:
    765       result = self._run(None, fetches, feed_dict, options_ptr,
--> 766                          run_metadata_ptr)
    767       if run_metadata:
    768         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

C:\Anaconda\envs\carnd-term1\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    922 
    923           if isinstance(subfeed_val, ops.Tensor):
--> 924             raise TypeError('The value of a feed cannot be a tf.Tensor object. '
    925                             'Acceptable feed values include Python scalars, '
    926                             'strings, lists, or numpy ndarrays.')

TypeError: The value of a feed cannot be a tf.Tensor object. Acceptable feed values include Python scalars, strings, lists, or numpy ndarrays.
In [ ]: